module.exports = function(app, settings){
	var debug 		= require('debug')('console')
		, log4js 		= require('log4js')
		, _					= require('lodash')
		, express 	= require('express')
		, util 			= require('util')
		, url 			= require('url')
		, csrf 			= require('csurf') // ref: https://github.com/expressjs/csurf
		, cls 			= require('../../libs/continuationLocalStorage')
		, randomstring = require("randomstring")
		, csrfProtection = csrf({ cookie: true })
		, models   = require('../../models');

	var router 		= express.Router()
		, logger 		= log4js.getLogger('console')
		, namespace = cls.getNamespace()
		, User 			= models.User;

	router.route('/')
		.get(function(req, res, next){
			var userToken = res.locals.userToken; //User principal
			debug(" thread local : " + userToken);
			return res.render('users', { title: '用户',  userToken: userToken });
		});

	router.route('/add')
		.get(function(req, res, next){
			return res.render('users_add', { title: '新建用户' })
		})
		.post(function(req, res, next){
			//Create new user
			var form = req.body;
			debug(util.inspect(form));

			User.create(form)
				.then(function(user){
					debug(user);
					return res.redirect('/console/users/')
				})
				.catch(function(err){
					logger.debug(err);
					return res.status(500).json({
						success: false
						, errors: [{
							code: 12345
							, message: err.message
							, internalError: err
						}]
					})
				});
		});

	/**
   * User RESTFul API
   * GET users
   * http://identity.aivics.net/api/users/
   */
  router.get('/search', function(req, res, next){	//Get list
		User.findAll()
				.then(function(users){
					return res.json({
						success: true
						, data: users
					});
				})
				.catch(function(err){
					logger.debug(err);
					return res.status(404).json({
						success: false
						, errors: [{
							code: 12345
							, message: 'requested resource does not exist'
							, internalError: err
						}]
					})
				});
	});

	router.get('/:id', function(req, res, next){
		var attributes = req.query.attrs ? req.query.attrs.split(' ') : [];
		var includeAttributes = []
			, excludeAttributes = [];

		debug("attributes: ", attributes);

		for(var i=0; i < attributes.length; i++){
			if(attributes[i].startsWith('!')){
				excludeAttributes.push(attributes[i].substr(1));
			}else{
				includeAttributes.push(attributes[i]);
			}
		}

		if(!_.isEmpty(includeAttributes)){
			attributes.push('id');
			attributes = includeAttributes;
		}
		if(!_.isEmpty(excludeAttributes)){
			excludeAttributes.push('password');
			attributes = {
				exclude: excludeAttributes
			}
		}

		debug("attributes: ", attributes);

		var data = {};

		if(req.params.id){
			return models.User.findById(req.params.id, {
					attributes: attributes
				})
				.then(function(user){
					data = user.toJSON();

					return res.json({
						success: true
			      , data: data
					});
				})
				.catch(function(err){
					logger.debug(err);
					return res.status(404).json({
						success: false
						, errors: [{
							code: 12345
							, message: 'requested resource does not exist'
							, internalError: err
						}]
					})
				});
		}
		return res.json({
			success: true
      , data: data
		});
	});

	app.use('/users', router);
}
